package com.qimo.zuoyeoa.controller;


import com.github.pagehelper.PageInfo;
import com.qimo.zuoyeoa.entity.Meeting;
import com.qimo.zuoyeoa.service.MeetingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MeetingController {
    private static final Logger logger = LoggerFactory.getLogger(MeetingController.class);

    // 使用@Autowired注解标注的成员变量，可以有Spring框架自动为这个变量赋值
    // 所同值是@Service标注的该接口类型的实现类对象实例。
    @Autowired
    private MeetingService meetingService;

    @GetMapping("/meeting/meeting_add")
    public ModelAndView meetingAddView(){
        ModelAndView mav = new ModelAndView("meeting/meeting_add");
        List<Meeting> meetings= meetingService.findAll();
        mav.addObject("meetings",meetings);
        return mav;
    }
    @GetMapping("/meeting/meeting1")
    public ModelAndView meetingListView(
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("meeting/meeting1");
        // 调用服务方法查询分页的客户数据
        PageInfo<Meeting> page = meetingService.findByKeyword(pageNum,pageSize,keyword);
//        System.out.println(page);
        mav.addObject("page",page);
        return mav;
    }


    @GetMapping("/meeting/meeting_modify")
    public ModelAndView meetingModifyView(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("meeting/meeting_modify");
        // 调用服务方法根据ID查询编辑客户
        Meeting meeting = meetingService.findById(id);
        mav.addObject("meeting",meeting);
        return mav;
    }

    @PostMapping("/meeting/meeting_add")
    // @Validated注解所标注的参数，表明该参数中的属性取值必须要按照属性上定义的验证规则进行验证，验证是由框架完成的。
    // 验证的结果会以BindingResult实例的形式传入到该方法中
    public ModelAndView meetingAdd(@Validated Meeting meeting, BindingResult bindingResult){

        // redirect表示重定向响应
        // 给浏览器发送一个请求地址，而没有任何试图内容或数据。
        // 浏览器会使用收到的地址，重新发送一个Get请求。由于是新请求，因此没有缓存上一次请求的数据，从而达到防止重复提交表单的目的
        ModelAndView mav = new ModelAndView("redirect:/meeting/meeting_add");
        Map<String, String> errorMessages = new HashMap<>();
        if (bindingResult.hasErrors()){
            // 如果有验证错误信息，那么要进行处理

            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            // 错误信息放入到映射中
            for (FieldError error : fieldErrors) {
                // 从每一个域错误对象中取出域名称
                errorMessages.put(error.getField(), error.getDefaultMessage());
            }
            //
            mav.addObject("errorMessages",errorMessages);
            //
            mav.addObject("meeting",meeting);
            //
            mav.setViewName("meeting/meeting_add");
        }else {
            // 如果没有错误信息，验证通过，保存客户信息
            // 调用服务方法保存客户数据
            boolean result = meetingService.append(meeting);
            if (result) {
                logger.info("新增客户信息成功 - " + meeting);
            }else {
                logger.info("新增客户信息失败 - " + meeting);
            }
        }
        return mav;
    }

    @PostMapping("/meeting/meeting_modify")
    public ModelAndView meetingModify(
            Meeting meeting,
            @RequestParam(name = "pageNum", required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/meeting/meeting1?pageNum=" + pageNum + "&pageSize=" + pageSize +"&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = meetingService.modify(meeting);
        return mav;
    }

    @GetMapping("/meeting/meeting_remove")
    public ModelAndView meetingRemove(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/meeting/meeting1?pageNum=" + pageNum + "&pageSize=" + pageSize +"&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务方法根据ID查询编辑客户
        boolean result = meetingService.remove(id);
        return mav;
    }
}
